#!/bin/sh

# Unzip some files
sudo unzip /private/tmp/firefoxpiv/nss.zip -d /opt/local/lib/
sudo unzip /private/tmp/firefoxpiv/nspr.zip -d /opt/local/lib/
unzip /private/tmp/firefoxpiv/tools.zip -d /private/tmp/firefoxpiv/
unzip /private/tmp/firefoxpiv/certs.zip -d /private/tmp/firefoxpiv/certs/

#chmod -R o+r /private/tmp/firefoxpiv/

# Hide the /opt directory if not already hidden
/private/tmp/firefoxpiv/setfile -a V /opt/

# Grab a list of users
dscl . -list /Users NFSHomeDirectory | awk '/Users/ { print $2 }' > /private/tmp/firefoxpiv/ff_users

# Grab a list of certs
rm -rf /private/tmp/firefoxpiv/certs/__MACOSX
ls /private/tmp/firefoxpiv/certs > /private/tmp/firefoxpiv/ff_certs

while read FF_USER; do

	# Get the profile name for Firefox.  This is user based and a random path, sooo have to fudge a little..
	
	sudo rm -f ${FF_USER}/Library/Application\ Support/Firefox/Profiles/.DS_Store
	
	FF_PROFILE=$(ls ${FF_USER}/Library/Application\ Support/Firefox/Profiles > /private/tmp/firefoxpiv/ff_profile)

	while read FF_PROFILE; do

		# Set the PKI module for Firefox
		sudo /private/tmp/firefoxpiv/nss-modutil -dbdir ${FF_USER}/Library/Application\ Support/Firefox/Profiles/${FF_PROFILE}/ -add "OS X 10.6 PKCS11 shim" -libfile /usr/libexec/SmartCardServices/pkcs11/tokendPKCS11.so -force

# Set path for FF4 cause mozilla is stupid
sudo /private/tmp/firefoxpiv/nss-modutil -dbdir ${FF_USER}/Library/Application\ Support/Firefox/Profiles/ -add "OS X 10.6 PKCS11 shim" -libfile /usr/libexec/SmartCardServices/pkcs11/tokendPKCS11.so -force		

# Add SSL certificate trust thing to profiles

sudo echo 'user_pref("security.ssl.allow_unrestricted_renego_everywhere__temporarily_available_pref", true);' >> ${FF_USER}/Library/Application\ Support/Firefox/Profiles/prefs.js
sudo echo 'user_pref("security.ssl.allow_unrestricted_renego_everywhere__temporarily_available_pref", true);' >> ${FF_USER}/Library/Application\ Support/Firefox/Profiles/${FF_PROFILE}/prefs.js

		echo "Installed PKCS11 Library for $FF_USER"
	
			while read FF_CERTS; do
			
			# Add the required cert chain to firefox.  
			sudo /private/tmp/firefoxpiv/nss-certutil -d $FF_USER/Library/Application\ Support/Firefox/Profiles/$FF_PROFILE/ -A -i "/private/tmp/firefoxpiv/certs/${FF_CERTS}" -n "${FF_CERTS}" -t "CT,C,C"

			# Add the required cert chain to firefox 4 cause mozilla is stupid
			sudo /private/tmp/firefoxpiv/nss-certutil -d $FF_USER/Library/Application\ Support/Firefox/Profiles/ -A -i "/private/tmp/firefoxpiv/certs/${FF_CERTS}" -n "${FF_CERTS}" -t "CT,C,C"			
			echo "Installed $FF_CERTS for $FF_USER in $FF_USER/Library/Application\ Support/Firefox/Profiles/"

			done < /private/tmp/firefoxpiv/ff_certs
	
	done < /private/tmp/firefoxpiv/ff_profile

done < /private/tmp/firefoxpiv/ff_users

# Cleanup the files from /private/tmp/
rm -rf /private/tmp/firefoxpiv/
